package de.tsystems.jsfdict.api.impl;

import de.tsystems.jsfdict.model.Language;
import de.tsystems.jsfdict.model.Translation;
import de.tsystems.jsfdict.model.Word;
import org.springframework.stereotype.Repository;

import javax.inject.Named;
import java.util.List;

@Named("wordDao")
@Repository
class WordDaoImpl extends AbstractDao<Word> implements WordDao {
    @Override
    public Class<Word> getEntityClass() {
        return Word.class;
    }

    @Override
    public Word findByTextAndLanguage(String text, Language language) {
        return (Word) getCurrentSession()
                .createQuery("from Word word where word.text=:name and language=:language")
                .setParameter("name", text)
                .setParameter("language", language)
                .uniqueResult();
    }

    @Override
    public Word create(String text, Language language) {
        Word word = new Word();
        word.setLanguage(language);
        word.setText(text);
        return save(word);
    }

    @Override
    public List<Translation> getTranslations(Word word) {
        return getCurrentSession()
                .createQuery("from Translation as translation " +
                        "inner join translation.left as lword " +
                        "inner join translation.right as rword " +
                        "where lword.id=:wordId or rword.id=:wordId"
                )
                .setParameter("wordId", word.getId()).list();
    }
}
